"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : GUC
Case Name   : 设置参数log_destination为'stderr,csvlog'，重启数据库成功
Create At   : 2023/01/09
@zou_jialiang0501145550
Description :
    1、查询log_destination默认值,show remote_read_mode;
    2、修改log_destination为stderr,csvlog，重启数据库使参数生效
    3、恢复默认值；
Expect      :
    1、显示默认值；
    2、参数修改成功；
    3、恢复默认值成功；
History     :
"""

import unittest
import os
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH

logger = Logger()


class GucTestCase(unittest.TestCase):
    def setUp(self):
        logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.constant = Constant()
        self.comsh = CommonSH('PrimaryDbUser')
        self.show_cmd = 'show log_destination'
        status = self.comsh.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status)

    def test_guc(self):
        logger.info("-----step1:查询log_destination;"
                    "expect:默认值为stderr-----")
        cmd1 = self.comsh.execut_db_sql(self.show_cmd)
        logger.info(cmd1)
        self.assertEqual("stderr", cmd1.split("\n")[-2].strip())

        logger.info("-----step2:修改log_destination为stderr,csvlog;"
                    "expect:修改成功-----")
        res1 = self.comsh.execute_gsguc('set', self.constant.GSGUC_SUCCESS_MSG,
                                        "log_destination = 'stderr,csvlog'")
        self.assertTrue(res1)

        logger.info("-----step3:查询修改后的参数;expect:修改参数成功-----")
        result = self.comsh.restart_db_cluster()
        logger.info(result)
        status = self.comsh.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status)
        cmd2 = self.comsh.execut_db_sql(self.show_cmd)
        logger.info(cmd2)
        self.assertEqual("stderr,csvlog", cmd2.split("\n")[-2].strip())

    def tearDown(self):
        logger.info("-----step4:恢复环境;expect:恢复环境成功-----")
        cmd4 = self.comsh.execut_db_sql(self.show_cmd)
        logger.info(cmd4)
        self.comsh.execute_gsguc('set', self.constant.GSGUC_SUCCESS_MSG,
                                     "log_destination = 'stderr'")
        result = self.comsh.restart_db_cluster()
        logger.info(result)
        status = self.comsh.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status)
        logger.info(f"-----{os.path.basename(__file__)} stop-----")